package com.traffic.between.adaptor;

import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;
import com.traffic.between.annotation.ChooseProvider;
import com.traffic.between.config.OrderInfoContext;
import com.traffic.between.redis.running.BsmOrderResultExecutor;
import com.traffic.between.service.ChenXiangServiceImpl;
import com.traffic.managent.service.order.bean.OrderBean;
import net.sf.json.JSONObject;

@ChooseProvider(channel = "cxkj")
public class ChenXiangAdaptor implements IAdaptor{

	private static Logger log = Logger.getLogger(ChenXiangAdaptor.class);

	public void order() {
		
		OrderBean orderBean = OrderInfoContext.getContext();
		orderBean.setSendTime(new Date());
		String productId = orderBean.getProductCode();
		String phoneNo = orderBean.getPhoneNo();
		String cstmOrderNo = orderBean.getIds();
		
		String result = ChenXiangServiceImpl.service.order(productId, phoneNo, cstmOrderNo);
		log.info("between- 晨祥科技流量订购接口返回结果："+result+",该订单号为:"+cstmOrderNo);

		
		JSONObject json = JSONObject.fromObject(result);
		String code = json.getString("code");
		

		if ("0000".equals(code)) {
			orderBean.setMessage(json.getString("msg"));
			orderBean.setErrorMsg("订单受理中");
			orderBean.setStatus("11");
		} else {
			orderBean.setMessage(json.getString("msg"));
			orderBean.setErrorMsg("订购失败");
			orderBean.setStatus("8");
		}
		BsmOrderResultExecutor.service.setOrder(orderBean);
	}

	
	public void status() {

		/**
		 * 0：订单已受理，1：订购中，7：订购成功，8：订购失败 { "code": "0000", "msg": "成功", "data": {
		 * "orderNo": "GDP14656954660051458", "cstmOrderNo": "test1234567"
		 * "status": "8", "errorDesc": "该用户是黑名单用户" } }
		 * 
		 */
		OrderBean orderBean = OrderInfoContext.getContext();
		String cstmOrderNo = orderBean.getIds();
		log.info("between -晨祥科技流量订购状态查询接口请求参数 ：cstmOrderNo:" + cstmOrderNo);
		String result = ChenXiangServiceImpl.service.orderStatus(cstmOrderNo);

		JSONObject json = JSONObject.fromObject(result);

		String code = json.getString("code");

		if ("0001".equals(code)) {
			orderBean.setStatus("8");
			orderBean.setErrorMsg("充值失败");
			orderBean.setMessage(json.getString("msg"));
		}
		Map<String, String> resultMap = (Map<String, String>) json.get("data");
		String status = resultMap.get("status");
		if ("0000".equals(code)) {
			orderBean.setMessage(json.getString("msg"));
			if ("0".equals(status)) {
				orderBean.setStatus("0");
				orderBean.setErrorMsg("受理中");
			} else if ("1".equals(status)) {
				orderBean.setStatus("1");
				orderBean.setErrorMsg("订购中");
			} else if ("7".equals(status)) {
				orderBean.setStatus("7");
				orderBean.setErrorMsg("订购成功");
			} else {
				
				orderBean.setStatus("8");
				orderBean.setErrorMsg("订购失败");
			}
		} else {
			
			// 延迟原因：改为订购中
			orderBean.setMessage(json.getString("msg"));
			orderBean.setStatus("1");
			orderBean.setErrorMsg("订购中");
		}
		BsmOrderResultExecutor.service.setOrder(orderBean);
	}
}
